package com.hl233.framework.demo;

import com.hl233.framework.BootApplication;
import com.hl233.framework.utils.DateUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;

/**
 * @author 张振强15065206763
 * @create 2024-09-06
 */
@SpringBootTest(classes = BootApplication.class)
public class GetDataSource {

    @Autowired
    private DataSource dataSource;

    @Test
    public void dataSourceInfo(){
//        dataSource.getConnection().
    }

    @Test
    void test() throws Exception {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = dataSource.getConnection();
            String sql = "INSERT INTO kafka_data_1 (context, createtime, val) VALUES (?, ?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "测试druid");
            pstmt.setString(2, DateUtil.dateToString(new Date(), DateUtil.FMT_Y_M_D_H_M_S));
            pstmt.setInt(3, 10086);
            pstmt.execute();
//            conn.commit();
        } catch (SQLException e) {
            try {
                if (conn != null) {
                    conn.rollback(); // 在发生异常时回滚事务
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
